<template>
<div class="pass">
	<div class="logout" @click="logout">
		<div class="logout-icon"></div>
		<div class="text">注销</div>
	</div>

	<div class="area">
		      <div class="making-area-auto" ref="booking" style="marigin-top: 0">
        <div class="area-header booking-header-color">
           <div class="square" style="background-color:red"></div>
          <div class="header-content">17分钟一桌菜</div>
          <div style="margin-left:160px">
            <el-link style="cursor: pointer;" type="danger" :underline="false" @click="statDetail"
                >详情</el-link
              >
          </div>
        </div>
        <div>
          <div style="font-size: 14px;
    padding: 15px;">
<!-- <<<<<<< HEAD

			<p>1.今日[超:{{biData.bizTimeoutNum}}单-{{biData.kscTimeoutNum}}菜]</p>
			<p>2.今日均:{{biData.kscTime}}分钟/菜,历史最优:{{biData.kscHisTime}}分钟/菜</p>
			<p>3.今日总:{{biData.bizNum}}单-{{biData.kscNum}}菜 </p>
-->
<p>1.今日<span style="color: red;"><b>超:</b></span>{{biData.bizTimeoutNum}}单-{{biData.kscTimeoutNum}}菜,占比{{biData.kscTimeoutPer}}%</p>
            <p style="margin-top:5px">2.今日<span style="color: red;"><b>均:</b></span>{{biData.kscTime}}分钟/菜，历史最优：{{biData.kscHisTime}}分钟/菜</p>
            <p style="margin-top:5px">3.今日<span style="color: red;"><b>总:</b></span>{{biData.bizNum}}单-{{biData.kscNum}}菜 </p>

          </div>
        </div>
      </div>
		<div class="making-area-auto" ref="booking">
			<div class="area-header booking-header-color" @click="refresh">
				<div class="square blue"></div>
				<div class="header-content">预定区</div>
			</div>
			<div class="booking-scroll">
				<div class="area-items">
					<div class="desk" v-for="(item,i) in bookingArea" v-bind:key="i" @click="showDetail(item.id)" :data-idx="i"
					 :data-type="1">
						<div class="desk-tag blue">
							<span class="desk-tag-text">预</span>
						</div>
						<div class="desk-detail">
							<div class="desk-number">{{ item.tableName }}</div>
							<div class="desk-time">预定{{ item.scheduleTime }}</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<div class="making-area-auto" ref="making">
			<div class="area-header making-header-color" @click="refresh">
				<div class="square yellow"></div>
				<div class="header-content">制作区</div>
			</div>
			<div class="making-scroll">
				<div class="area-items">
					<div  v-for="(item,i) in makingArea" v-bind:key="i" @click="showDetail(item.id)">
						<div v-if="item.callStatus==0">
						<div class="desk " v-if="new Date().getTime()-new Date(item.callUpTime).getTime()<780000">
							<div class="desk-tag" :class="item.isJumped?'brown':''">
								<span class="desk-tag-text">{{item.isJumped?'插':''}}</span>
							</div>
							<div class="desk-detail">
                  				<div class="desk-time">{{ item.tableName }}</div>
								<div class="desk-number">{{ item.waitTime }}</div>
							</div>
						</div>
						<div class="desk circle-y" v-if="new Date().getTime()-new Date(item.callUpTime).getTime()>780000 && new Date().getTime()-new Date(item.orderTime).getTime()<1020000">
							<div class="desk-tag" :class="item.isJumped?'brown':''">
								<span class="desk-tag-text">{{item.isJumped?'插':''}}</span>
								</div>
							<div class="desk-detail">
								<div class="desk-time">{{ item.tableName }}</div>
								<div class="desk-number">{{ item.waitTime }}</div>
							</div>
						</div>
							<div class="desk circle-r " v-if=" new Date().getTime()-new Date(item.callUpTime).getTime()>1020000">
								<div class="desk-tag" :class="item.isJumped?'brown':''">
								<span class="desk-tag-text">{{item.isJumped?'插':''}}</span>
								</div>
							<div class="desk-detail">
								<div class="desk-time">{{ item.tableName }}</div>
								<div class="desk-number">{{ item.waitTime }}</div>
							</div>
						</div>
					</div>
					<div v-if="item.callStatus==1">
						<div class="desk ">
							<div class="desk-tag" :class="item.isJumped?'brown':''">
								<span class="desk-tag-text">{{item.isJumped?'插':''}}</span>
							</div>
							<div class="desk-detail">
                  				<div class="desk-time">{{ item.tableName }}</div>
								<div class="desk-number">00分00秒</div>
							</div>
						</div>
					</div>
					</div>
				</div>
			</div>
		</div>

		<div class="waiting-area" ref="waiting" style="height: 200px;">
			<div class="area-header waiting-header-color" @click="refresh">
				<div class="square light-green"></div>
				<div class="header-content">等待区</div>
			</div>
			<div class="waiting-scroll" >
				<div class="area-items">
					<div v-for="(item,i) in waitingArea" v-bind:key="i" @click="showDetail(item.id)">
					<div v-if="item.callStatus==0">
						<div class="desk " v-if="new Date().getTime()-new Date(item.callUpTime).getTime()<780000">
							<div class="desk-detail">
								<div class="desk-time">{{ item.tableName }}</div>
								<div class="desk-number">{{ item.waitTime }}</div>
							</div>
						</div>
						<div class="desk circle-y" v-if="new Date().getTime()-new Date(item.callUpTime).getTime()>780000 && new Date().getTime()-new Date(item.orderTime).getTime()<1020000"  >
							<div class="desk-detail">
								<div class="desk-time">{{ item.tableName }}</div>
								<div class="desk-number">{{ item.waitTime }}</div>
							</div>
						</div>
						<div class="desk circle-r"  v-if=" new Date().getTime()-new Date(item.callUpTime).getTime()>1020000">
							<div class="desk-detail">
								<div class="desk-time">{{ item.tableName }}</div>
								<div class="desk-number">{{ item.waitTime }}</div>
							</div>
						</div>
					</div>
					<div v-if="item.callStatus==1">
						<div class="desk">
							<div class="desk-detail">
								<div class="desk-time">{{ item.tableName }}</div>
								<div class="desk-number">00分00秒</div>
							</div>
						</div>
					</div>
					</div>
				</div>
			</div>
		</div>

		<div class="button-box">
			<div class="cus-button" @click="viewHistory">
				<span class="button-content">传菜查询</span>
			</div>
		</div>

	</div>
	<div class="list">
		<div class="finish-food" ref="cookedList" v-if="cookedList && cookedList.length>0">
			<div class="list-header list-green" @click="refresh"><span class="list-content">成品熟食</span></div>

			<div class="food-items cooked-items">
				<div class="food-item" v-for="(item,i) in cookedList" v-bind:key="i">
					<div class="name">{{ item.itemName }}</div>
					<div class="amount">{{ item.lastQty ? 'x' + item.lastQty : '' }}</div>
					<div class="seat">
						<div class="seat-item">{{ item.tableName }}
							<span v-if="item.remark ||(item.method && item.method.length>0)">
								（<span v-if="item.remark">{{item.remark}} / </span><span v-for="(label, j) in item.method" :key="j"><span v-if="j>0"> | </span>{{ label }}</span>）
							</span>
						</div>
					</div>
					<div class="type">{{ item.sourceType === 1?'堂食':(item.sourceType === 2?'外卖':'零售')}}</div>
					<div class="time">
						<div class="time-item ">
							{{ '下单时间：' + item.shortOrderTime }}
						</div>
					</div>
					<div class="action">
						<div class="list-button" :class="item.status!=2?'list-button-disabled':''" @click="passon4List(0, i)">
							<div class="list-button-content">传</div>
						</div>
					</div>
				</div>
			</div>

		</div>
		<div class="cooking-food">
			<div class="list-header list-blue" @click="refresh"><span class="list-content">厨房制作中</span></div>

			<div class="waiting-item-scroll" :style="{height: waitingFoodHeight + 'px'}">

				<div class="food-items">
					<div  v-for="(item,i) in makingList" v-bind:key="i">
						<div v-if="item.itemId!=='5992900000000000213'" class="food-item">
								<div class="name"><b v-if="item.status=='2'">{{ item.itemName }}</b><span v-if="item.status!='2'">{{ item.itemName }}</span></div>
								<div class="amount"><b v-if="item.status=='2'">{{ item.lastQty ? 'x' + item.lastQty : '' }}</b><span v-if="item.status!='2'">{{ item.lastQty ? 'x' + item.lastQty : '' }}</span></div>
								<div class="seat">
									<div class="seat-item"><b v-if="item.status=='2'">{{ item.tableName }}</b><span v-if="item.status!='2'">{{ item.tableName }}</span>
										<span v-if="item.remark ||(item.method && item.method.length>0)">
											（<span v-if="item.remark">{{item.remark}} / </span><span v-for="(label, j) in item.method" :key="j"><span v-if="j>0"> | </span>{{ label }}</span>）
										</span>
										<div v-if="item.isJumped" class="seat-item-tag brown">插</div>
									</div>
								</div>
								<!-- <div class="type">{{ item.sourceType === 1?'堂食':(item.sourceType === 2?'外卖':'零售')}}</div> -->
								<div class="time">
									<div class="time-item ">
										{{ '下单时间：' + item.shortOrderTime }}
									</div>
								</div>
								<div class="action">
									<div class="list-button" :class="item.status!=2? 'list-button-disabled':''" @click="passon4List(1, i)">
										<div class="list-button-content"><b>{{item.status==2?'传':(item.status==3?'取消':'待配')}}</b></div>
									</div>
								</div>
							</div>
					</div>
				</div>

			</div>

		</div>

		<el-dialog :visible.sync="detailVisible" v-if="detailVisible" center top="8vh" width="800px" custom-class="dialog-box">
			<div v-if="detailInfo.remark" style="color: red;text-align: left;font-size: 16px;margin-left:40px;margin-top:-30px;">整单备注：{{detailInfo.remark}}</div>
			<div class="dialog-items">
				
				<div v-for="(item,i) in detailInfo.list" v-bind:key="i" class="dialog-row">
					<div class="dialog-item">
						<div class="dialog-item-name">{{ item.itemName }}
							<span v-if="item.method && item.method.length>0">
								（<span v-for="(label, j) in item.method" :key="j"><span v-if="j>0"> | </span>{{ label }}</span>）
							</span>
						</div>
						<div class="dialog-item-amount">{{ item.lastQty ? 'x' + item.lastQty : '' }}</div>
						<div class="dialog-item-status" v-if="item.status==1" style="color: red;">{{ item.statusName}}</div>
				<div class="dialog-item-status" v-else-if="item.status==2" style="color: orange;">{{ item.statusName}}</div>
				<div class="dialog-item-status" v-else  >{{ item.statusName}}</div>
						<div class="dialog-item-time">下单时间：{{ item.orderTime }}</div>
					</div>
					<div class="dialog-action white button-yellow" v-if="item.status==1 && !item.isJumped" @click="jumpItem(item.kscIds)">插</div>
					<div class="dialog-action " v-else-if="item.status==1 && item.isJumped" >已插</div>
					<div class="dialog-action white button-yellow" v-else-if="item.status==2" @click="passon4Item(item)">传</div>
					<div class="dialog-action white button-dark dialog-button-text" v-else-if="item.status==3" @click="passon4Item(item)">取消</div>
					<div class="dialog-action" v-else></div>
				</div>
			</div>
			<div slot="title" class="dialog-title">{{ dialogTitle }}<b>（{{detailInfo.list[0].sscount}}人）</b></div>
			<div slot="footer" class="dialog-footer">
				<div class="dialog-button button-yellow" @click="jumpOrder">
					<span class="dialog-button-text white">整单插队</span>
				</div>
				<div class="dialog-button button-dark" @click="setBooking">
					<span class="dialog-button-text white">设置预定</span>
				</div>
				<div class="dialog-button" @click="detailVisible = false">
					<span class="dialog-button-text">退出</span>
				</div>
			</div>
		</el-dialog>


		<el-dialog :visible.sync="scheduleVisible" center width="480px" custom-class="dialog-box">
			<div class="dialog-items">
				<el-radio-group v-model="scheduleInfo.scheduled">
				<div class="radio-box">
					<div class="radio-item">
						<el-radio :label="true" class="radio">预定时间：</el-radio>
					</div>
					<div class="time-item">
						<!-- <el-time-select v-model="scheduleInfo.time" 
						:picker-options="{
							start: minTime,
							step: '00:15',
							end: '23:00'
						  }"
						 placeholder="请选择时间">
						</el-time-select> -->
              <el-select v-model="scheduleInfo.hours" placeholder="请选择" style="width:100px">
                <el-option
                  v-for="(index,item) in 24"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
              <el-select v-model="scheduleInfo.minutes" placeholder="请选择" style="width:100px">
                <el-option
                  v-for="(index,item) in 60"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
					</div>

				</div>
				<div class="radio-box">
					<el-radio :label="false">取消预定</el-radio>
				</div>
				</el-radio-group>
			</div>
			<div slot="title" class="dialog-title">预定设置</div>
			<div slot="footer" class="dialog-footer">
				<div class="dialog-button setting-button" @click="scheduleVisible = false">
					<span class="dialog-button-text">取消</span>
				</div>
				<div class="dialog-button setting-button button-dark" @click="saveBooking">
					<span class="dialog-button-text white">确认</span>
				</div>
			</div>
		</el-dialog>

	</div>

</div>
</template>


<script>
import websocketUtil from "../websocketUtil.js"
import api from "../api.js"
import util from "../util.js"

let intervalId;

export default {
	data() {
		return {
			bookingArea: [],
			makingArea: [],
			waitingArea: [],
			cookedList: [],
			makingList: [],
			waitingHeight: 292,
			waitingFoodHeight: 292,
			detailVisible: false,
			dialogTitle: '',
			detailBsId: null,
			detailInfo: [],
			scheduleVisible: false,
			dialogTableVisible:false,
			normalData: [],
      timeOutData:[],
			scheduleInfo: {},
			radio: '2',
			goalTime: '',
			minTime:  '09:00' ,
			activeName:'first',
			 myInterval:null,
			biData:{},
		}
	},
	
	mounted: function() {
		// please call these method to calculate waiting-area height when data change
		this.getWaitingHeight()
		this.getWaitingListHeight()

		window.localStorage.setItem("homepage", "passon");
		this.curUser = util.getCurLoginUser();
		websocketUtil.connectWebSocket([{
			key: api.WS_REFRESH_PASSON,
			action: this.refresh
		}]);
		this.refresh();
		//  this.getBiData();
		intervalId = setInterval(this.refreshWaitTime, 1000);
		this.myInterval =setInterval( this.getBiData,5000)
	},
	
	destroyed: function() {
		websocketUtil.disconnectWebSocket();
		clearInterval(intervalId);
		clearInterval(this.myInterval)
	},

	methods: {
    getBiData(){
      util.request(this,api.getBizOrderBi,{},"GET").then(res=>{
        this.biData=res.data
        console.log("resres", this.biData)
      })
    },
		getWaitingHeight: function() {
			this.waitingHeight = 768 - 12 * 2 - 60 - this.$refs.booking.offsetHeight - this.$refs.making.offsetHeight
		},
		getWaitingListHeight: function() {
			let cookedListHeight = this.$refs.cookedList ? this.$refs.cookedList.offsetHeight : 0;
			this.waitingFoodHeight = 768 -32 - cookedListHeight;
		},

		logout: function() {
			util.logout();
			this.$router.replace({
				name: "login"
			});
		},

		refresh: function() {
			this.queryOrderInfo();
			this.queryCookedItems();
			this.queryMakingItems();
		},

		queryOrderInfo: function() {
			util.request(this, api.GetOrderInfos, {
					needPrepared: true
				}, "GET")
				.then(res => {
					this.bookingArea = res.data.booking;
					this.makingArea = res.data.making;
					this.waitingArea = res.data.waiting;
					this.$nextTick(this.getWaitingHeight);
				})
				.catch(err => {
					this.$message.error(err.data.errmsg);
				})
		},

		queryCookedItems: function() {
			util.request(this, api.GetCookedItems, {}, "GET")
				.then(res => {
					let cookedList = res.data ? res.data : [];
					cookedList.forEach(item => {
						item.shortOrderTime = util.dateTimeToTime(item.orderTime);
					})
					this.cookedList = cookedList;
					this.$nextTick(this.getWaitingListHeight);
				})
				.catch(err => {
					this.$message.error(err.data.errmsg);
				})
		},

		queryMakingItems: function() {
			util.request(this, api.GetMakingItems, {}, "GET")
				.then(res => {
					let makingList = res.data ? res.data : [];
					makingList.forEach(item => {
						item.shortOrderTime = util.dateTimeToTime(item.orderTime);
					})
					this.makingList = makingList;
				})
				.catch(err => {
					this.$message.error(err.data.errmsg);
				})
		},

		refreshWaitTime: function() {
			if (this.bookingArea) {
				let temp = [].concat(this.bookingArea);
				temp.forEach(item => {
					item.waitTime = util.calcWaitTime(item.orderTime);
				})
				this.bookingArea = temp;
			}
			if (this.makingArea) {
				let temp = [].concat(this.makingArea);
				temp.forEach(item => {
					item.waitTime = util.calcWaitTime(item.callUpTime,true);
				})
				this.makingArea = temp;
			}
			if (this.waitingArea) {
				let temp = [].concat(this.waitingArea);
				temp.forEach(item => {
					item.waitTime = util.calcWaitTime(item.callUpTime,true);
				})
				this.waitingArea = temp;
			}
		},

		showDetail: function(bsId) {
			this.detailBsId = bsId;
			this.dialogTitle = ""
			util.request(this, api.GetOrderDetail, {
					bsId: bsId
				}, "GET")
				.then(res => {
					if (res.data.list) {
						res.data.list.forEach(item => {
							if (item.status == 1) {
								item.statusName = '待配';
							} else if (item.status == 2) {
								item.statusName = '待传';
							} else if (item.status == 3) {
								item.statusName = '完成';
							} else {
								item.statusName = '  ';
							}
						})
					}
					this.detailInfo = res.data;
					if (res.data.list && res.data.list.length > 0) {
						this.dialogTitle = res.data.list[0].tableName;
					}
					this.detailVisible = true;
				})
				.catch(err => {
					this.$message.error(err.data.errmsg);
				})
		},


		passon4List: function(type, index) {
			let list = (type == 0)?this.cookedList: this.makingList;
			this.passon4Item(list[index]);
		},

		passon4Item: function(item) {
			 
			if (item.status < 2 ) {
				this.$message({type: "error", message:"菜品尚未制作，不能操作！"});
				return ;
			}
			let passed = (item.status == 2  );
			util.request(this, api.SavePasson, {kscIds: item.kscIds, passed}, "PUT")
				.then(() => {
					 this.showDetail(item.bsId)
				})
				.catch(err => {
					this.$message.error(err.data.errmsg);
				})
		},
		
		detailAllPrepared: function() {
			let allPrepared = true;
			let whiteList=['5992900000000000005','5992900000000001627','5992900000000002112'];
			this.detailInfo.list.forEach(item => {
				if (item.status == 1 || whiteList.includes(item.itemId)) {
					allPrepared = false;
				}
			})	
			return allPrepared;
		},
		
		setBooking: function() {
			if (!this.detailBsId) return;
			
			if (!this.detailInfo ||!this.detailInfo.list || this.detailInfo.list.length < 1) {
				this.$message.warning("无订单详情！");
				return;
			}
			
/**       if (this.detailAllPrepared()) {
        this.$message.error("该订单已全部配菜，无法预定！");
        return;
      }**/

			util.request(this, api.GetOrderSchedule, {bsId: this.detailBsId}, "GET")
				.then(res => {
					this.scheduleInfo = res.data;
					this.scheduleInfo.scheduled=true
					var date = new Date();
					date.setMinutes(date.getMinutes() + 17);
					this.scheduleInfo.hours=date.getHours();
					this.scheduleInfo.minutes=util._normalizeNumber(date.getMinutes());
					this.scheduleVisible = true;
				})
				.catch(err => {
					this.$message.error(err.data.errmsg);
				})
		},
		
		saveBooking: function() {			
			let message = this.scheduleInfo.scheduled ? "确认保存该订单为预定吗？": "确认取消该订单预定吗？"
			if (!confirm(message)) return;
			this.scheduleInfo.time=util._normalizeNumber(this.scheduleInfo.hours)+":"+util._normalizeNumber(this.scheduleInfo.minutes)
			util.request(this, api.SaveOrderSchedule, this.scheduleInfo, "POST")
				.then(() => {
					this.scheduleVisible = false;
					this.detailVisible = false;
				})
				.catch(err => {
					this.$message.error(err.data.errmsg);
				})
		},
		statDetail: function () {
			this.$router.push({
					path: "test"
				});
    //   this.dialogTableVisible = true;
    //   util
    //     .request(
    //       this,
    //      "/v2/{shopId}/histories/ksc?needException=false",
    //       {
    //         needException: false,
    //       },
    //       "GET"
    //     )
    //     .then((res) => {
    //       this.normalData=res.data
    //     })
    //     .catch((err) => {
    //       this.$message.error(err.data.errmsg);
    //     });
    //     util
    //     .request(
    //       this,
    //      "/v2/{shopId}/histories/ksc?needException=true",
    //       {
    //         needException: true,
    //       },
    //       "GET"
    //     )
    //     .then((res) => {
    //       this.timeOutData=res.data
    //     })
    //     .catch((err) => {
    //       this.$message.error(err.data.errmsg);
    //     });
    },
		jumpOrder: function() {
			if (this.detailAllPrepared()) {
				this.$message.error("该订单已全部配菜，无需再插队！");
				return ;
			}
			util.request(this, api.SaveJumpingOrder, {bsId: this.detailBsId}, "POST")
				.then(() => {
					this.detailVisible = false;
				})
				.catch(err => {
					this.$message.error(err.data.errmsg);
				})
		},
		
		jumpItem: function(kscIds) {
			let data = {bsId: this.detailBsId, kscIds:kscIds};
			util.request(this, api.SaveJumpingItem, data, "POST")
				.then(() => {
					this.showDetail(this.detailBsId)
					// this.detailVisible = false;
				})
				.catch(err => {
					this.$message.error(err.data.errmsg);
				})
		},
		
		viewHistory: function() {
			this.$router.push({
					name: "passonhist"
				});
		},

	},

}
</script>

<style lang="css" scoped>
	@import "~@/assets/css/pass-and-dish.css";
	@import "~@/assets/css/common.css";
	@keyframes blink {
0% {
opacity: 0;
}
50% {
opacity: 0.5;
}
100% {
opacity: 1;
}
}
.circle-r{
	background-color: #f58f98;
	animation: blink 2s infinite;
}
.circle-y{
	background-color: yellow;
	animation: blink 2s infinite;
}
</style>
